<template>
    <div>
        <div class="common-wrapper-top">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item>当前位置：</el-breadcrumb-item>
                <el-breadcrumb-item>设备中心</el-breadcrumb-item>
                <el-breadcrumb-item :to="{path: '/devicelist'}">设备管理</el-breadcrumb-item>
                <el-breadcrumb-item>编辑设备</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="commom-top-right">
                <el-button size="mini" @click="returnBack" type="primary">返回</el-button>
            </div>
        </div>
        <div class="common-top-gray-line"></div>
        <div class="device-title-wrapper">
            <i class="el-icon-mobile"></i>
            <span>设备信息</span>
        </div>

        <div class="device-row">
            <div class="device-cell">
                <span class="cell-title">设备名称</span>
                <el-input size="medium" v-model="name" placeholder="请输入设备名称"></el-input>
                <span class="must">*</span>
            </div>
            <div class="device-cell">
                <span class="cell-title">设备类型</span>
                <el-select class="flex-1" v-model="equipmentTypeIndex" size="medium" placeholder="请选择设备类型">
                    <el-option :value="index" :label="item.name" v-for="(item,index) in equipmentTypes" :key="item.id">
                    </el-option>
                </el-select>
                <span class="must">*</span>
            </div>

            <div class="device-cell mb35">
                <span class="cell-title">园区名称</span>
                <el-select class="flex-1" @change="chooseVillage" v-model="villageIndex" size="medium"
                    placeholder="请选择园区名称">
                    <el-option v-for="(item,index) in villages" :value="index" :label="item.village_name"
                        :key="item.id">
                    </el-option>
                </el-select>
                <div @click="addVillage()" class="ml-10 addOtherbtn" >新增园区</div>
                <span class="must">*</span>
                <div class="hint_show" v-if="villageIndex!==''">{{villages[villageIndex].province_name}}{{villages[villageIndex].city_name}}{{villages[villageIndex].area_name}}</div>
            </div>
            
            <div class="device-cell mb35">
                <span class="cell-title">详细地址</span>
                <el-input size="medium" style="width: 300px;" class="flex-1" v-model="address"
                    placeholder="请输入内容,例如北京天坛">
                    <el-button @click="showMapDialog" size="medium" slot="append" icon="el-icon-map-location">
                    </el-button>
                </el-input>
                <span class="must">*</span>
            </div>

            <div class="device-cell">
                <span class="cell-title">周边功能</span>
                <el-switch v-model="open_nearby"></el-switch>
                <span class="must">*</span>
            </div>

            

            <div class="device-cell" v-show="false">
                <span class="cell-title">园区地址</span>
                <el-input size="medium" :value="villageIndex!==''?villages[villageIndex].province_name:''" disabled></el-input>
                <span class="ml-20">-</span>
                <el-input size="medium" :value="villageIndex!==''?villages[villageIndex].city_name:''" disabled></el-input>
                <span class="ml-20">-</span>
                <el-input size="medium" :value="villageIndex!==''?villages[villageIndex].area_name:''" disabled></el-input>
            </div>


            
        </div>
        <div class="device-row">
            <div class="device-cell" style="align-items: flex-start; width: 100%;">
                <span class="cell-title">设备照片</span>
                <el-upload accept="image/*" :file-list="uploadImg" :on-preview="handlePictureCardPreview"
                    :before-upload="beforeUpload" :limit="maxUploadNumber" :action="uploadUrl" :on-error="uploadError"
                    :on-remove="handleRemove" :on-exceed="uploadExceed" :on-progress="uploadProgress"
                    :on-success="uploadSuccess" list-type="picture-card">
                    <i slot="default" class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </div>
        </div>

        <div class="device-title-wrapper" style="margin-top: -20px;">
            <i class="el-icon-cpu"></i>
            <span>主板信息</span>
        </div>
        <div class="device-row">
            <div class="device-cell">
                <span class="cell-title">主板数量</span>
                <el-select disabled class="flex-1" @change="chooseMainboard" v-model="mainboardIndex" size="medium"
                    placeholder="请选择主板数量">
                    <el-option :value="index" :label="item.name" v-for="(item,index) in mainboard" :key="item.id">
                    </el-option>
                </el-select>
                <span class="must">*</span>
            </div>
        </div>
        <div class="device-row" style="align-items: flex-start;">
            <div class="device-column" v-for="(item,index) in mainboardConfig" :key='index'>
                <div class="device-cell device-buttom">
                    <span class="cell-title">主板{{index+1}}</span>
                    <el-input size="medium" v-model="item.equipment_name" placeholder="请输入主板名称" maxlength="11"></el-input>
                    <span class="must opticy">*</span>
                </div>
                <div class="device-cell ">
                    <span class="cell-title"></span>
                    <el-input disabled size="medium" v-model="item.equipment_number" placeholder="请输入主板编号"></el-input>
                    <span class="must">*</span>
                </div>
                


                <transition-group name="el-zoom-in-top">
                    <template v-if="item.config">
                        <div class="config" v-for="(subItem,subIndex) in item.config" :key='subIndex'>
                            <div class="condfig-cell" v-if="subItem.length>1">
                                <span class="config-title">打水口名称</span>
                                <el-input size="medium" class="flex-1" v-model="subItem.outlet_name" placeholder="请输入打水口名称">
                                </el-input>
                            </div>
                            <div class="condfig-cell">
                                <span class="config-title">价格模板</span>
                                <el-select class="flex-1" v-model="subItem.templateIndex" size="medium"
                                    placeholder="请选择价格模板">
                                    <el-option :value="index" :label="item.template_title"
                                        v-for="(item,index) in templates" :key="item.id">
                                    </el-option>
                                </el-select>
                                <div @click="onlineTemplateFun(index,subIndex)" class="ml-10 addOtherbtn" >新增模板</div>
                            </div>
                            <div class="condfig-cell" v-if="subItem.templateIndex!==''">
                                <span class=" config-title">打水配置</span>
                                <el-tag size="medium" class="m-l-20" effect="dark"
                                    v-for="(item,index) in templates[subItem.templateIndex].template" :key='index'>
                                    {{item.rise}}升/{{item.money}}元</el-tag>
                            </div>
                        </div>
                    </template>
                </transition-group>
            </div>
        </div>

        <el-button size="medium" @click="submit" class="submit-btn" :loading="loadingSubmit" type="primary">保存
        </el-button>

        <el-dialog custom-class="device-add-map-dialog" :close-on-click-modal="false"
            :visible.sync="dialogTableVisible">
            <div class="map-wrapper">

                <el-autocomplete size="medium" class="map-input" v-model="address" :fetch-suggestions="querySearchAsync"
                    placeholder="请输入内容,例如北京天坛" :trigger-on-focus="false" @select="handleSelect">
                    <template slot-scope="{ item }">
                        <div class="custom-li">
                            <div class="auto-name">{{ item.title }}</div>
                            <span class="auto-addr">{{ item.address }}</span>
                        </div>
                    </template>
                </el-autocomplete>


                <div id="container"></div>
                <div class="map-alert">
                    <el-alert title="选择园区后，地图为何不能正常显示？" type="info">
                        <p>地图是根据选择的园区定位来展示的，如果地图不能正常显示，则该园区的地图配置有误，请在园区重新配置。</p>
                    </el-alert>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import QQMapWX from '@/lib/js/qqmap-jssdk'
    var tencentMap = new QQMapWX();
    let qqMap, qqMarker;
    export default {
        name: "deviceadd",
        data() {
            return {
                longitude: 116.397572, //经度
                latitude: 39.908518, //纬度
                name: '',//设备名称
                address: '',
                mainboard: [],// 主板
                mainboardIndex: '',//主板index
                templates: [],//打水模板
                templateIndex: '',//打水模板index
                equipmentTypes: [],//设备类型
                equipmentTypeIndex: '',//设备类型index
                villages: [],//园区
                villageIndex: '',//园区index
                dialogTableVisible: false,
                open_nearby: true,
                mainboardConfig: [],//主板配置
                lastMainboardConfig: [],//存取上一次的主板数据
                loadingSubmit: false,
                maxUploadNumber: 1,
                uploadUrl: process.env.API_ROOT + "Common/Common/upload",
                dialogVisible: false,
                dialogImageUrl: '',
                uploadImg: [],
                village_id:'', //新增中返回的--园区id
                template_id:'',//新增中返回的--模板id
                curindex:0,//当前主板下标
                tapIndex:0,//当前打水口
            }
        },
        created() {
            Promise.all([
                this.fetchResult("Common/Common/getEquipmentType"),
                this.fetchResult("Common/Equipment/getEquipmentConfig"),
                this.fetchResult("Partner/Village/templateList", {
                    page: 1,
                    row: 99,
                    template_species: "2",
                    is_add_global_template: true,
                }),
                this.fetchResult("Partner/WaterCard/getPartnerVillage", {
                    row: 9999,
                    page: 1
                }),
            ]).then(([equipmentTypes, mainboard, templates, villages]) => {
                this.mainboard = mainboard;
                this.templates = templates.data;
                this.equipmentTypes = equipmentTypes;
                this.villages = villages;
                this.getEquipment();
            })
        },
        //进入之前
        beforeRouteEnter(to, from, next) {
                to.meta.keepAlive = true;
                    next(vm => {
                //console.log('to>>>>>',from.query.is_device,to.meta.village_id)
                //新增的园区id  to.meta.village_id
                var village_id=to.meta.village_id?to.meta.village_id:'';
                if(from.query.is_device==1&&village_id){
                        vm.choosebackVillage(village_id);
                        vm.village_id=village_id;
                }
                //新增的模板id to.meta.template_id
                var template_id=to.meta.template_id?to.meta.template_id:'';
                if(from.query.is_device==1&&template_id){
                        vm.choosebackTemlate(template_id);
                        vm.template_id=template_id;
                }
            })
        },
        //离开之前
        beforeRouteLeave(to, from, next) {
                let updates = ["/onlineTemplate", "/communityAdd"];
                if (updates.includes(to.path)) {
                    from.meta.keepAlive = true;
                } else {
                    from.meta.keepAlive = false;
        }
        //console.log('from',this.village_id,from.path,from.meta)
        //console.log('to',this.village_id,to.path,to.meta)
                next();
		},
        methods: {
                  //回显快捷添加打水模板 重新抓取一次模板列表
            choosebackTemlate(template_id){
                //console.log('获取到的打水模板',template_id);
                Promise.all([
                this.fetchResult("Partner/Village/templateList", {
                    page: 1,
                    row: 99,
                    template_species: "2",
                    is_add_global_template: true,
                    order:'ASC',//升序仅仅PC
                })
                ]).then(([ templates]) => {
                
                var templatesArr=templates.data;
                this.templates = templatesArr;
                var mainboard_Config=JSON.parse(JSON.stringify(this.mainboardConfig)),curindex=this.curindex,tapIndex=this.tapIndex;
                templatesArr.forEach((item,index)=>{
                    if(item.id==template_id){
                        mainboard_Config[curindex].config[tapIndex].templateIndex=index;
                        this.mainboardConfig=mainboard_Config;
                        this.$forceUpdate()
                    }
                })
                })
            },
            //回显快捷园区 重新抓一次园区列表
            choosebackVillage(village_id){
                var villages=this.villages;
                Promise.all([
                    this.fetchResult("Partner/WaterCard/getPartnerVillage", {
                    row: 9999,
                    page: 1
                    }),
                ]).then(([villages]) => {
                    this.villages = villages;
                    villages.forEach((item,index)=>{
                    if(village_id==item.id){
                    this.villageIndex=index;
                    this.chooseVillage(index)
                    }
                })
                })
            },
             //增加园区入口
            addVillage(){
                this.$router.push({ path: '/communityAdd', query: { is_device: 1 } });
            },
             //快捷添加打水模板
            onlineTemplateFun(index,subIndex){
                this.curindex=index;
                this.tapIndex=subIndex;
                this.$router.push({ path: '/onlineTemplate', query: { is_device: 1 } });
            },
            getEquipment() {
                this.$post({
                    url: "Partner/Equipment/detail",
                    data: {
                        equipment_control_id: this.$route.query.id,
                    }, success: res => {
                        if (res.code > 0) {
                            //console.log(res.data);
                            const source = res.data;
                            let equipmentTypeIndex = this.equipmentTypes.findIndex(item => item.id == source.equipment_control_type_id)
                            let villageIndex = this.villages.findIndex(item => item.id == source.village_id);
                            let mainboardIndex = this.mainboard.findIndex(item => item.id == source.equipment_quantity_id);
                            const equipment_info = source.equipment_info;
                            let mainboardConfig = [];
                            equipment_info.forEach(item => {
                                let origin = item.outlet_data;
                                let config = [];
                                origin.forEach(current => {
                                    let templateIndex = this.templates.findIndex(element => element.id == current.set_template_id)
                                    config.push({
                                        outlet_name: current.outlet_name,
                                        templateIndex: ~templateIndex ? templateIndex : ''
                                    });
                                })
                                mainboardConfig.push({
                                    equipment_number: item.equipment_number,
                                    equipment_name: item.equipment_name,
                                    config,
                                })
                            });

                            this.name = source.name;
                            this.address = source.address;
                            this.villageIndex = ~villageIndex ? villageIndex : "";
                            this.equipmentTypeIndex = ~equipmentTypeIndex ? equipmentTypeIndex : "";
                            this.mainboardIndex = ~mainboardIndex ? mainboardIndex : "";
                            this.open_nearby = source.open_nearby == 1 ? true : false,
                                this.longitude = source.longitude;
                            this.latitude = source.latitude;
                            this.mainboardConfig = mainboardConfig;

                            let uploadImg = [];
                            source.equipment_img_whole.forEach(item => {
                                let arr = item.split("/");
                                let url = arr[arr.length - 1];
                                if (url) {
                                    uploadImg.push({
                                        name: "",
                                        url: item,
                                        short_url: url,
                                    });
                                }
                            })
                            this.uploadImg = uploadImg;
                        } else {
                            this.$message.error(res.message);
                        }
                    },
                    error: e => {
                        this.$message.error("网络错误");
                    }
                })
            },




            //选择主板数量
            chooseMainboard(val) {
                const mainboard = this.mainboard[val];
                let quantity = mainboard.equipment_quantity;
                let mainboardConfig = [];
                for (let i = 0; i < quantity; i++) {
                    mainboardConfig.push({
                        equipment_number: ''
                    })
                }
                this.mainboardConfig = mainboardConfig;
            },

            querySearchAsync(queryString, cb) {
                tencentMap.getSuggestion({ keyword: queryString }).then(res => {
                    res.forEach(item => {
                        res.value = res.title
                    })
                    cb(res)
                });

            },

            handleSelect(item) {
                this.address = item.title;
                let location = item.location;
                this.longitude = location.lng;
                this.latitude = location.lat;
                qqMap.panTo(new qq.maps.LatLng(this.latitude, this.longitude));
                qqMarker.setPosition(new qq.maps.LatLng(this.latitude, this.longitude))
            },

            showMapDialog() {
                this.dialogTableVisible = true;
                // qqMap.panTo(new qq.maps.LatLng(this.latitude, this.longitude));
                // qqMarker.setPosition(new qq.maps.LatLng(this.latitude, this.longitude))
                if (!qqMap) {
                    this.initMap();
                } else {
                    qqMap.panTo(new qq.maps.LatLng(this.latitude, this.longitude));
                    qqMarker.setPosition(new qq.maps.LatLng(this.latitude, this.longitude))
                }

            },

            chooseVillage(val) {
                const village = this.villages[val];
                this.latitude = village.lat;
                this.longitude = village.lng;
                this.address = village.address;
                // qqMap.panTo(new qq.maps.LatLng(this.latitude, this.longitude));
                // qqMarker.setPosition(new qq.maps.LatLng(this.latitude, this.longitude))
            },

            initMap() {
                this.TMap("2CZBZ-RKRK3-HGJ3G-YH2G2-GIL3T-LHBFD").then(qq => {
                    let center = new qq.maps.LatLng(this.latitude, this.longitude);
                    qqMap = new qq.maps.Map(document.getElementById("container"), {
                        center: center,
                        zoom: 14
                    });
                    qqMarker = new qq.maps.Marker({
                        position: center,
                        draggable: true,
                        map: qqMap
                    });
                    qq.maps.event.addListener(qqMarker, 'dragend', () => {
                        var currentPosition = qqMarker.getPosition();
                        this.latitude = currentPosition.lat;
                        this.longitude = currentPosition.lng;
                        //console.log(currentPosition);
                    });

                });
            },

            submit() {
                if (this.name == '') {
                    this.$message.error("请输入设备名称"); return false;
                }
                if (this.equipmentTypeIndex === '') {
                    this.$message.error("请选择设备类型"); return false;
                }
                if (this.villageIndex === '') {
                    this.$message.error("请选择园区"); return false;
                }
                if (this.address == "") {
                    this.$message.error("请输入详细地址"); return false;
                }
                if (this.latitude == "" || this.longitude == "" || this.longitude == "0" || this.latitude == "0") {
                    this.$message.error("请点击详细地址的定位图标，重新定位"); return false;
                }
                let mainboardConfig = this.mainboardConfig;
                //console.log(mainboardConfig, "mainboardConfig")
                let equipment_data = [];
                for (let i = 0; i < mainboardConfig.length; i++) {
                    if (mainboardConfig[i].equipment_number == "") {
                        this.$message.error(`主板编号未填写`);
                        return false;
                    }
                    let outlet_data = [];
                    let config = mainboardConfig[i].config;
                    if (config) {
                        for (let j = 0; j < config.length; j++) {
                            if (config[j].templateIndex === "") {
                                this.$message.error(`请选择线上打水配置`);
                                return false;
                            }
                            outlet_data.push({
                                name: config[j].outlet_name,
                                set_template_id: this.templates[config[j].templateIndex].id
                            })
                        }
                    }
                    equipment_data.push({
                        equipment_number: mainboardConfig[i].equipment_number,
                        equipment_name: mainboardConfig[i].equipment_name,
                        outlet_data,
                    });
                }
                let village = this.villages[this.villageIndex];

                const url_arrs = [];
                this.uploadImg.forEach(item => {
                    url_arrs.push(item.short_url);
                })
                this.loadingSubmit = true;
                this.$post({
                    url: "Partner/Equipment/edit",
                    data: {
                        equipment_control_id: this.$route.query.id,
                        name: this.name,
                        longitude: this.longitude,
                        latitude: this.latitude,
                        village_id: village.id,
                        address: this.address,
                        equipment_quantity_id: this.mainboard[this.mainboardIndex].id, // 主板数量ID
                        province: village.province,
                        city: village.city,
                        area: village.area,
                        province_name: village.province_name,
                        city_name: village.city_name,
                        area_name: village.area_name,
                        equipment_control_type_id: this.equipmentTypes[this.equipmentTypeIndex].id, //设备类型
                        equipment_img: url_arrs, //设备图片
                        open_nearby: this.open_nearby == true ? 1 : 2,
                        equipment_data, //主板信息
                    }, success: res => {
                        this.loadingSubmit = false;
                        if (res.code > 0) {
                            this.$message.success(res.message);
                            setTimeout(() => { this.returnBack() }, 1500);
                        } else {
                            this.$message.error(res.message)
                        }
                    }, error: e => {
                        this.loadingSubmit = false;
                        this.$message.error("网络错误");
                    }
                })
            },


            //异步加载腾讯地图处理
            TMap(key) {
                return new Promise(function (resolve, reject) {
                    window.init = function () {
                        resolve(qq)//注意这里
                    }
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = `https://map.qq.com/api/js?v=2.exp&key=${key}&callback=init`;
                    script.onerror = reject;
                    document.head.appendChild(script);
                })
            },

            //ajax 查询结果 返回promise对象
            fetchResult(url, data) {
                return new Promise((resolve, reject) => {
                    this.$post({
                        url,
                        data,
                        success: res => {
                            if (res.code > 0) {
                                resolve(res.data);
                            } else {
                                reject(res.message);
                            }
                        }, error: e => {
                            reject("网络错误");
                        }
                    })
                });
            },
            //返回
            returnBack() {
                this.$router.back(-1);
            },


            uploadExceed() {
                this.$message.error(`最多只能上传${this.maxUploadNumber}张图片`);
            },


            beforeUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过2MB!');
                }
                return isLt2M;
            },



            uploadProgress() {
                this.loading = this.$loading({
                    lock: true,
                    text: '图片上传中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            },

            uploadError() {
                this.loading.close();
            },


            uploadSuccess(e, file, fileList) {
                this.loading.close();
                if (e.code === 1000) {
                    this.uploadImg.push(
                        {
                            name: "",
                            url: e.data.all_url,
                            short_url: e.data.url,
                        }
                    );
                } else {
                    this.$message.error(e.message);
                }
            },

            handleRemove(file, fileList) {
                this.uploadImg = fileList;
            },

            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            }
        },
    }
</script>
<style scoped>
.opticy{
    opacity: 0;
  }
    .device-title-wrapper {
        color: #2C5586;
        font-weight: bold;
        padding: 30px 0 25px 30px
    }

    .device-row {
        width: 1000px;
        justify-content: space-between;
        display: flex;
        align-items: center;
        padding-left: 60px;
        flex-wrap: wrap;
    }

    .device-cell {
        width: 450px;
        margin-bottom: 25px;
        display: flex;
        align-items: center;
        position: relative;
    }
     .device-buttom{
    margin-bottom: 5px;
  }

    .device-cell .cell-title {
        width: 80px;
        flex-shrink: 0;
        color: #4D4D4D;
        font-weight: 400;
    }
     .mb35{
        margin-bottom: 35px;
    }
    .hint_show{
        position: absolute;
        bottom: -18px;
        left: 95px;
        font-size: 12px;
        color: #2C5586;
    }
    .must {
        margin-left: 5px;
        color: #ff0000;
    }

    .flex-1 {
        flex: 1;
    }

    .ml-20 {
        padding: 0 3px;
        text-align: center;
        color: #ccc;
    }

    #container {
        /*地图(容器)显示大小*/
        width: 100%;
        height: 500px;
    }

    .map-input {
        width: 300px;
        margin-bottom: 10px;
    }

    .map-alert {
        margin-top: 10px;
    }

    .auto-name {
        text-overflow: ellipsis;
        overflow: hidden;
        font-size: 14px;
    }

    .auto-addr {
        font-size: 12px;
        color: #b4b4b4;
        margin: 0;

        list-style: none;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .custom-li {
        line-height: 24px !important;
    }

    .question {
        position: absolute;
        right: -25px;
        color: #999;
        cursor: pointer;
    }

    .ml-10 {
        margin-left: 10px;
    }
    .addOtherbtn{
        cursor: pointer;
        color: #2C5586;
        font-size: 12px;
    }

    .device-column .device-cell {
        margin-bottom: 10px;
    }


    .config {
        box-sizing: border-box;
        background: #F2F2F2;
        border-radius: 10px;
        padding: 5px 15px 15px;
        width: 450px;
        margin-bottom: 10px;
    }


    .condfig-cell {
        display: flex;
        align-items: center;
        margin-top: 10px;
    }

    .config-title {
        width: 100px;
        flex-shrink: 0;
        color: #4D4D4D;
        font-size: 14px;
    }

    .m-l-20 {
        margin-right: 20px;
    }

    .submit-btn {
        margin-top: 50px;
        margin-left: 60px;
        margin-bottom: 50px;
    }
</style>
<style>
    .device-add-map-dialog {
        width: 1000px !important;
    }

    .device-add-map-dialog .el-dialog__body {
        padding-top: 0 !important;
    }
</style>